﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using System.Net.Mail;
using Domain.NetworkService;
using System.Net.NetworkInformation;
using System.Diagnostics;
using Domain.Entities;

namespace Domain
{
    public static class EmailSender
    {
        static List<KeyValuePair<string, Type>> list = new List<KeyValuePair<string, Type>>();
        static object _lock = new object();
        /// <summary>
        ///  
        /// </summary>
        /// <param name="to"></param>
        /// <param name="body"></param>
        /// <param name="subject"></param>
        /// <param name="fromAddress"></param>
        /// <param name="fromDisplay"></param>
        /// <param name="credentialUser"></param>
        /// <param name="credentialPassword"></param>
        public static void checkAndSend(NetworkTestResult ntr, string deviceName)
        {
            var item = new KeyValuePair<string, Type>(deviceName, ntr.GetType());
            if (ntr as EchoResult == null && !list.Contains(item) && (ntr.Status == ResultStatus.Failed))
            {
                AddToAndSend(ntr, deviceName, item);
            }
            else if (ntr as EchoResult != null && !list.Contains(item))
            {
                EchoResult er = ntr as EchoResult;
                if (er.Status != IPStatus.Success)
                {
                    AddToAndSend(ntr, deviceName, item);
                    Debug.WriteLine(list.Count);
                    foreach (var itm in list)
                    {
                        Debug.WriteLine("{0} {1}", itm.Key, itm.Value);
                    }
                }
            }
            else if (list.Contains(item) && ntr.Status == ResultStatus.Success)
            {
                RemoveItem(item);
            }
            else if (ntr as EchoResult != null)
            {
                if (((EchoResult)ntr).Status == IPStatus.Success)
                {
                    RemoveItem(item);
                }
            }
        }

        private static void RemoveItem(KeyValuePair<string, Type> item)
        {
            lock (_lock)
            {
                list.Remove(item);
            }
        }

        private static void AddToAndSend(NetworkTestResult ntr, string deviceName, KeyValuePair<string, Type> item)
        {
            lock (_lock)
            {
                list.Add(item);
            }
            SecureStringManager ssm = new SecureStringManager();
            string EmailTo = ConfigurationManager.AppSettings["EmailTo"];
            string EmailFrom = ConfigurationManager.AppSettings["EmailFrom"];
            string EmailUser = ConfigurationManager.AppSettings["EmailUser"];
            string EmailPassword = ssm.Unprotect(ConfigurationManager.AppSettings["EmailPassword"]);
            Email(EmailTo,
                  ntr.ToString(),
                  "Проблема с \"" + deviceName + "\"",
                  EmailFrom,
                  "Network Information",
                  EmailUser,
                  EmailPassword);
        }
        private static void Email(string to,
                         string body,
                         string subject,
                         string fromAddress,
                         string fromDisplay,
                         string credentialUser,
                         string credentialPassword)
        {
            string host = ConfigurationManager.AppSettings["SmtpServer"];
            try
            {
                MailMessage mail = new MailMessage();
                mail.Body = body;
                mail.IsBodyHtml = true;
                mail.To.Add(new MailAddress(to));
                mail.From = new MailAddress(fromAddress, fromDisplay, Encoding.UTF8);
                mail.Subject = subject;
                mail.SubjectEncoding = Encoding.UTF8;
                mail.Priority = MailPriority.Normal;
                SmtpClient smtp = new SmtpClient();
                smtp.Credentials = new System.Net.NetworkCredential(credentialUser, credentialPassword);
                smtp.Host = host;
                smtp.Send(mail);
            }
            catch(Exception ex)
            {
                StringBuilder sb = new StringBuilder(1024);
                sb.Append("\nTo:" + to);
                sb.Append("\nbody:" + body);
                sb.Append("\nsubject:" + subject);
                sb.Append("\nfromAddress:" + fromAddress);
                sb.Append("\nfromDisplay:" + fromDisplay);
                sb.Append("\nHosting:" + host);
                DBWorker dbWorker = new DBWorker();
                dbWorker.WriteLog(String.Format("Не могу отправить письмо. {0}", ex.Message), MessageType.Error);
            }
        }
    }
}
